import tkinter as tk
from tkinter import ttk, scrolledtext
import logging


class LogViewer(ttk.Frame):
    """日志视图"""

    def __init__(self, parent, controller):
        super().__init__(parent)
        self.controller = controller

        # 创建UI
        self.create_widgets()

        # 配置日志重定向
        self.setup_log_redirect()

    def create_widgets(self):
        """创建控件"""
        # 日志控制面板
        control_frame = ttk.Frame(self)
        control_frame.pack(fill=tk.X, padx=5, pady=5)

        self.clear_btn = ttk.Button(control_frame, text="清除日志", command=self.clear_log)
        self.clear_btn.pack(side=tk.LEFT, padx=5)

        self.save_btn = ttk.Button(control_frame, text="导出日志", command=self.export_log)
        self.save_btn.pack(side=tk.LEFT, padx=5)

        # 日志文本框
        self.log_text = scrolledtext.ScrolledText(
            self,
            wrap=tk.WORD,
            width=80,
            height=15,
            state=tk.DISABLED
        )
        self.log_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

    def setup_log_redirect(self):
        """设置日志重定向"""
        log_handler = logging.StreamHandler(self)
        log_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
        logging.getLogger().addHandler(log_handler)

    def write(self, message):
        """写入日志到文本框"""
        self.log_text.config(state=tk.NORMAL)
        self.log_text.insert(tk.END, message)
        self.log_text.see(tk.END)
        self.log_text.config(state=tk.DISABLED)

    def flush(self):
        """刷新方法 (占位)"""
        pass

    def clear_log(self):
        """清除日志"""
        self.log_text.config(state=tk.NORMAL)
        self.log_text.delete(1.0, tk.END)
        self.log_text.config(state=tk.DISABLED)

    def export_log(self):
        """导出日志到文件"""
        # 在实际应用中实现文件保存对话框
        logging.info("导出日志功能被调用")